package com.fastadmin.config;

import com.fastadmin.common.jedis.JedisTemplate;
import io.lettuce.core.RedisClient;
import io.netty.util.concurrent.FastThreadLocal;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class RedisUtilConfig {
    public static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();
    private String host;
    private Integer port;
    private Integer database;
    private String password;
    private Integer timeout;
    private Integer maxTotal;
    private Integer maxIdle;
    private final JedisPoolConfig JEDIS_POOL_CONFIG = new JedisPoolConfig() {{
        setMaxTotal(this.getMaxTotal());
        setMaxIdle(this.getMaxIdle());
    }};

    private final FastThreadLocal<JedisTemplate> FTL = new FastThreadLocal<JedisTemplate>() {
        @Override
        protected JedisTemplate initialValue() {
            log.debug("mFastThreadLocal :{}", "RedisProvider 连接池初始化 ");
            JedisPool vJedisPool = new JedisPool(
                    JEDIS_POOL_CONFIG,
                    host,
                    port,
                    timeout,
                    password,
                    database);
            JedisTemplate instance = new JedisTemplate(vJedisPool);
            log.debug("initValue JedisPool  :{}, CurrentThread :{} ,Total :{}", instance, Thread.currentThread(), ATOMIC_INTEGER.incrementAndGet());
            return instance;
        }
    };

    @Bean(name = "jedisTemplate")
    @Scope( ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public JedisTemplate jedisTemplate() {
        return FTL.get();
    }


}
